package utils;

import java.sql.Connection;
import java.util.Collections;
import java.util.HashMap;

import org.eclipse.jetty.websocket.WebSocket.Outbound;


import data.*;
import jsonobj.*;

public class ClientFunctions implements Msg  {
	
	public ClientFunctions() {}
	
	public Response registerUser(Connection conn,RegisterInfo ri)
	{
		UserInfo ui;
		if((ui = Database.users.get(ri.user)) != null)
			return new Response(false,USR_ERR);
		//TODO add email check from SQL
		if(!SSHUtils.RegisterUser(ri.user, ri.pass)) return new Response(false,ERR);
		ui = new UserInfo(ri);
		Database.users.put(ri.user, ui);
		Database.clusters.put(ri.user, Collections.synchronizedMap(new HashMap<String,ClusterInfo>() ));
		if(Database.registerUser(conn, ui) == SQL_ERR) return new Response(false,SQL_ERR);
		return new Response(true,OK);
		
	}
	
	public Object userLogin(Connection conn, LoginInfo li)
	{
		String uname = li.user;
		String passwd = li.pass;
		UserInfo ui;
		if((ui = Database.users.get(uname)) == null)
		{
			return new Response(false,USR_ERR);
		}
		if(!ui.getPasswd().equals(passwd))
		{
			return new Response(false,PWD_ERR);
		}
		if(ui.isConnected)
		{
			return new Response(false,ERR);
		}
		return ui;
	}
}
